<template>
  <div :class="className" :style="{height:height}" />
</template>

<script>
import echarts from 'echarts'

require('echarts/theme/macarons') // echarts theme
import resize from '@/views/dashboard/mixins/resize'

export default {
  name: 'StatisticalChart',
  mixins: [resize],
  props: {
    className: {
      type: String,
      default: 'chart'
    },
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '350px'
    },
    autoResize: {
      type: Boolean,
      default: true
    },
    chartData: {
      type: Object,
      required: true,
      default: {}
    }
  },
  data() {
    return {
      chart: null,
      searchKey: {}
    }
  },
  watch: {
    chartData: {
      handler: function(newVal, oldVal) {
        this.setOptions(newVal)
      },
      deep: true
      // immediate: true
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.initChart()
    })
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    this.chart.dispose()
    this.chart = null
  },
  methods: {
    initChart() {
      this.chart = echarts.init(this.$el, 'macarons')
      this.setOptions(this.chartData)
    },
    setOptions({ list = [], permission = '' }) {
      const date = []
      const salary = []
      const piao = []
      const reissueMoney = []
      for (var i = 0; i < list.length; i++) {
        date.push(list[i].ym)
        salary.push(list[i].salaryMoney)
        piao.push(list[i].invoiceMoney)
        reissueMoney.push(list[i].reissueMoney)
      }
      this.chart.setOption({
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
            crossStyle: {
              color: '#999'
            }
          }
        },
        toolbox: {
          feature: {
            dataView: { show: false, readOnly: false },
            magicType: { show: false, type: ['line', 'bar'] },
            restore: { show: false },
            saveAsImage: { show: false }
          }
        },
        legend: {
          data: ['月薪工资', '补发工资', '开票金额']
        },
        xAxis: [
          {
            type: 'category',
            data: date
          }
        ],
        yAxis: [
          {
            type: 'value',
            name: '金额',
            min: 0,
            axisLabel: {
              formatter: '{value}'
            }
          }
        ],
        series: [
          {
            name: '月薪工资',
            type: 'bar',
            stack: '总量',
            data: salary
          },
          {
            name: '补发工资',
            type: 'bar',
            stack: '总量',
            data: reissueMoney
          },
          {
            name: '开票金额',
            type: 'line',
            data: piao
          }
        ]
      })
    }
  }
}
</script>
